<?php


namespace app\controller\admin;


use app\BaseController;
use app\common\Consts;
use app\common\lists\ListsSearchTrait;
use app\common\lists\ListsSortTrait;
use app\models\user\AdminUserModel;
use think\App;

abstract class BaseAdminController extends BaseController implements SearchInterface
{
    use ListsSearchTrait;
    use ListsSortTrait;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->params = $app->request->param();
        $this->initWhere();
        $this->initSort();
    }

    public function getSearch()
    {
        return $this->setSearch();
    }

    public function initWhere()
    {
        if (!($this instanceof SearchInterface)) {
            return [];
        }
        return $this->searchWhere = $this->createWhere($this->getSearch());
    }


    public function getSort()
    {
        return $this->setSort();
    }

    public function initSort()
    {
        if (!($this instanceof SearchInterface)) {
            return [];
        }
        return $this->createSort($this->getSort(), $this->request->param('order_by', 'id'), $this->request->param('sort', 'desc'));
    }

    protected function getBaseWhere($field)
    {
        $where = [];
        $userInfo = $this->request->userInfo;
        $roleId = $userInfo->role_id;
        if ($roleId == Consts::ADMIN_ROLE_ID) {
            return $where;
        }
        $userIdArr = AdminUserModel::where('referrer', 'like', '%' . $userInfo->id . '%')->column('id');
        array_push($userIdArr, $userInfo->id);
        $where[] = [$field, 'in', $userIdArr];
        return $where;
    }
}